﻿using Microsoft.AspNetCore.Mvc;
using OpenIddict.Abstractions;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace YDT_AuthServices.Controllers
{
    /// <summary>
    /// 应用控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ApplicationController : ControllerBase
    {
        public readonly IOpenIddictApplicationManager _applicationManager;

        public ApplicationController(IOpenIddictApplicationManager applicationManager)
        {
            _applicationManager = applicationManager;
        }

        // GET: api/<ApplicationController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<ApplicationController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // 1、添加Application【对客户端【使用token】的抽象】
        [HttpPost]
        public async Task CreateApplicationAsync(string ClientId, string ClientSecret, string DisplayName)
        {
            // 添加客户端【调用各个微服务的端】
            if (await _applicationManager.FindByClientIdAsync(ClientId) == null)
            {
                await _applicationManager.CreateAsync(new OpenIddictApplicationDescriptor
                {
                    ClientId = ClientId,
                    ClientSecret = ClientSecret,
                    DisplayName = DisplayName,
                    // 权限
                    Permissions =
                    {
                        // 端点Token权限
                        OpenIddictConstants.Permissions.Endpoints.Token,
            
                        // 授权类型权限
                        OpenIddictConstants.Permissions.GrantTypes.Password,
                        OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
            
                        // 作用域权限- 管理权限
                        OpenIddictConstants.Permissions.Prefixes.Scope + "manger" // 默认写死了
                    }
                });
                Console.WriteLine($"已注册 微服务客户端: {ClientId}");
            }
            else
            {
                Console.WriteLine("微服务客户端已存在");
            }
        }

        // PUT api/<ApplicationController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<ApplicationController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
